﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.MaterialManagements;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.MaterialManagements
{
    /// <summary>
    /// 规格单位显示Handler
    /// </summary>
    public class SearchSpecificationUnitHandler : IRequestHandler<SearchSpecificationUnitCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 物料服务表仓储
        /// </summary>
        public readonly IBaseRepository<SpecificationUnit> specificationUnitrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchSpecificationUnitHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="specificationUnitrepository"></param>
        /// <param name="logger"></param>
        public SearchSpecificationUnitHandler(IMapper mapper, IBaseRepository<SpecificationUnit> specificationUnitrepository, ILogger<SearchSpecificationUnitHandler> logger)
        {
            this.mapper = mapper;
            this.specificationUnitrepository = specificationUnitrepository;
            this.logger = logger;
        }
        /// <summary>
        /// 规格单位
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SearchSpecificationUnitCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var specificationUnit = await(await specificationUnitrepository.GetAll()).ToListAsync();
                //判断获取的数据不为空
                if (specificationUnit.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = specificationUnit;
                    result.Msg = "规格单位显示查询成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = " 规格单位显示查询失败" + ex.Message;
                logger.LogError(" 规格单位显示查询失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
